package com.chcit.handmedicine.database.model;

import java.lang.reflect.Method;
import java.util.HashMap;

import android.database.Cursor;

public class BaseModel {

	protected HashMap<String, Method> methodsMap;

	public HashMap<String, Method> getMethodsMap() {
		return methodsMap;
	}

	public BaseModel() {
		initSetMethodsMap();
	}
	
	public BaseModel(Cursor cursor) {
		initSetMethodsMap();
		fillWithData(cursor);
	}

	public void initSetMethodsMap() {
		Method[] methods = this.getClass().getMethods();
		methodsMap= new HashMap<String, Method>();
		for (Method method : methods) {
			if (method.getName().startsWith("set")) {
				methodsMap.put(method.getName().toUpperCase(), method);
			}
		}
	}
	
	public void fillWithData(Cursor cursor) {
		if (cursor != null) {
			try {
				for (int i = 0; i < cursor.getColumnCount(); i++) {
					String setMethodName = ("set" + cursor.getColumnName(i)).toUpperCase();
					if (methodsMap.containsKey(setMethodName)) {
						Method setMethod = methodsMap.get(setMethodName);
						if (setMethod.getParameterTypes()[0] == Integer.class) {
							setMethod.invoke(this, cursor.getInt(i));
						} else if (setMethod.getParameterTypes()[0] == String.class) {
							setMethod.invoke(this, cursor.getString(i));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("Data cast exception! " + e.getLocalizedMessage());
			}
		}
	}

}
